package avicit.bdp.dds.server.worker;

import avicit.bdp.common.utils.SpringApplicationContext;
import avicit.bdp.dds.common.Constants;
import avicit.bdp.dds.common.IStoppable;
import avicit.bdp.dds.common.thread.Stopper;
import avicit.bdp.dds.remote.NettyRemotingServer;
import avicit.bdp.dds.remote.command.CommandType;
import avicit.bdp.dds.remote.config.NettyServerConfig;
import avicit.bdp.dds.server.filter.BdpSpringTypeFilter;
import avicit.bdp.dds.server.log.LoggerServer;
import avicit.bdp.dds.server.master.MasterServer;
import avicit.bdp.dds.server.worker.config.WorkerConfig;
import avicit.bdp.dds.server.worker.processor.ShellExecuteProcessor;
import avicit.bdp.dds.server.worker.processor.TaskExecuteProcessor;
import avicit.bdp.dds.server.worker.processor.TaskKillProcessor;
import avicit.bdp.dds.server.worker.registry.WorkerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;

import javax.annotation.PostConstruct;

/**
 * worker server
 */
@ComponentScan(value = "avicit", excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {MasterServer.class}),
        @ComponentScan.Filter(type = FilterType.CUSTOM, classes = {BdpSpringTypeFilter.class})
})
@SpringBootApplication
public class WorkerServer implements IStoppable {

    /**
     * logger
     */
    private static final Logger logger = LoggerFactory.getLogger(WorkerServer.class);

    /**
     * netty remote server
     */
    private NettyRemotingServer nettyRemotingServer;

    /**
     * spring application context
     * only use it for initialization
     */
    @Autowired
    private SpringApplicationContext springApplicationContext;

    /**
     * worker registry
     */
    @Autowired
    private WorkerRegistry workerRegistry;

    /**
     * worker config
     */
    @Autowired
    private WorkerConfig workerConfig;

    private LoggerServer loggerServer;

    /**
     * worker server startup
     * <p>
     * worker server not use web service
     *
     * @param args arguments
     */
    public static void main(String[] args) {
        Thread.currentThread().setName(Constants.THREAD_NAME_WORKER_SERVER);
        new SpringApplicationBuilder(WorkerServer.class).web(WebApplicationType.NONE).run(args);
    }


    /**
     * worker server run
     */
    @PostConstruct
    public void run() {
        String threadName = Thread.currentThread().getName();
        if (threadName.equalsIgnoreCase(Constants.THREAD_NAME_API_SERVER)) {
            return;
        }

        logger.info("start logger server......");
        try {
            // 避免启动异常  造成spring启动失败
            loggerServer = new LoggerServer();
            loggerServer.start();
        } catch (Exception e) {
            try {
                loggerServer.stop();
            } catch (Exception e1) {
                logger.error("loggerServer failed : " + e1.getMessage(), e1);
            }
            logger.error("start loggerServer failed", e);
        }

        logger.info("start worker server......");

        //init remoting server
        NettyServerConfig serverConfig = new NettyServerConfig();
        serverConfig.setListenPort(workerConfig.getListenPort());
        this.nettyRemotingServer = new NettyRemotingServer(serverConfig);
        this.nettyRemotingServer.registerProcessor(CommandType.TASK_EXECUTE_REQUEST, new TaskExecuteProcessor());
        this.nettyRemotingServer.registerProcessor(CommandType.TASK_KILL_REQUEST, new TaskKillProcessor());
        this.nettyRemotingServer.registerProcessor(CommandType.SHELL_EXECUTE_REQUEST, new ShellExecuteProcessor());
        this.nettyRemotingServer.start();

        // worker registry
        this.workerRegistry.registry();

        //register hooks, which are called before the process exits
        Runtime.getRuntime().addShutdownHook(new Thread(() -> close("shutdownHook")));


    }

    public void close(String cause) {

        try {
            //execute only once
            if (Stopper.isStopped()) {
                return;
            }

            logger.info("worker server is stopping ..., cause : {}", cause);

            // set stop signal is true
            Stopper.stop();

            try {
                //thread sleep 3 seconds for thread quitely stop
                Thread.sleep(3000L);
            } catch (Exception e) {
                logger.warn("thread sleep exception", e);
            }

            this.nettyRemotingServer.close();
            this.workerRegistry.unRegistry();

            if (this.loggerServer != null) {
                this.loggerServer.stop();
            }


        } catch (Exception e) {
            logger.error("worker server stop exception ", e);
            System.exit(-1);
        }
    }

    @Override
    public void stop(String cause) {
        close(cause);
    }

}
